//
//  AAWActor.m
//  AAWGameCore
//
//  Created by David Wagner on 07/07/2009.
//  Copyright 2009 Appaweek. All rights reserved.
//

#import "AAWActor.h"
#import "AAWGame.h"

#pragma mark Private declarations
@interface AAWActor ()

@end


@implementation AAWActor

#pragma mark Properties

@synthesize red;
@synthesize green;
@synthesize blue;
@synthesize alpha;
@synthesize body;

#pragma mark Class methods

#pragma mark Instance methods

- (id)initWithGame:(AAWGame*)game andDefinition:(b2BodyDef*)definition
{
	if(self = [super init])
	{
		definition->userData = self;
		body = game.world->CreateBody(definition);
		
		[self setColourComponents:0 green:0 blue:0 alpha:255];
	}
	
	return self;
}

- (void)dealloc
{
	//NSLog(@"Actor getting destroyed: %@", self);
	
	body->GetWorld()->DestroyBody(body);
	body = nil;
	
	[super dealloc];
}

- (void)setColourComponents:(GLubyte)redValue green:(GLubyte)greenValue blue:(GLubyte)blueValue alpha:(GLubyte)alphaValue
{
	self.red   = redValue;
	self.green = greenValue;
	self.blue  = blueValue;
	self.alpha = alphaValue;
}

- (void)update
{

}

- (void)renderShapes
{
	b2Shape* curShape = body->GetShapeList();
	
	// Render the shapes that make up this body
	while (curShape != NULL) 
	{
		switch (curShape->GetType()) {
			case e_circleShape:
				
				break;
			case e_polygonShape:
				glPushMatrix();
				
				glTranslatef(body->GetPosition().x, body->GetPosition().y, 0);
				glRotatef(body->GetAngle() * (180.0f / M_PI), 0.0f, 0.0f, 1.0f);
				
				glVertexPointer(2, GL_FLOAT, 0, ((b2PolygonShape*)curShape)->GetVertices());
				glEnableClientState(GL_VERTEX_ARRAY);
				
				if( body->IsSleeping() )
				{
					glColor4ub(red, green, blue, alpha);
				}
				else
				{
					glColor4ub(green, blue, red, alpha);
				}
				
				glDrawArrays(GL_LINE_LOOP, 0, ((b2PolygonShape*)curShape)->GetVertexCount());
				
				glPopMatrix();
				break;
			default:
				NSLog(@"Unknown shape");
				break;
		}
		curShape = curShape->GetNext();
	}
}

- (void)renderJoints
{
	// Render the joints
	b2JointEdge* je = body->GetJointList();
	GLfloat points[4];
	while (je != NULL) {
		switch (je->joint->GetType()) {
			case e_revoluteJoint:
				break;
			case e_prismaticJoint:
				break;
			case e_distanceJoint:
				glPushMatrix();
				
				points[0] = je->joint->GetAnchor1().x;
				points[1] = je->joint->GetAnchor1().y;
				points[2] = je->joint->GetAnchor2().x;
				points[3] = je->joint->GetAnchor2().y;
				
				glVertexPointer(2, GL_FLOAT, 0, points);
				glColor4ub(255, 0, 255, 255);
				glDrawArrays(GL_LINE_STRIP, 0, 2);
				
				glPopMatrix();
				break;
			case e_pulleyJoint:
				break;
			case e_mouseJoint:
				break;
			case e_gearJoint:
				break;
			case e_unknownJoint:
			default:
				break;
		}
		
		je = je->next;
	}
}

- (void)render
{
	[self renderShapes];
	[self renderJoints];	
}

@end
